<template>
    <view class="cart-temp" :style="themeColor">
        <header-bar :config="config"></header-bar>
        <view class="main">
            <mescroll-uni
                v-if="isLoadOk"
                :height="height"
                ref="mescrollRef"
                @init="mescrollInit"
                :down="downOption"
                @down="refresh"
                :up="upOption"
                @up="getData"
                @emptyclick="emptyClick">
                <view class="header-action-bar header-action-bar-title" @click="isEdit = !isEdit">
                    <text class="car-title">购物车</text>
                    <text>{{ isEdit ? "完成" : "编辑" }}</text>
                </view>
                <view class="consignee flex-s-s" v-if="getUseAddress">
                    <view class="flex-start">
                        <view class="title">收货人</view>
                        <view class="name">{{ getUseAddress.ContactName }} {{ getUseAddress.ContactTel }}</view>
                    </view>
                    <view @click="goSelectAddress"
                        ><text class="style">切换</text
                        ><iconsfont customIcons="icon-xiayiji" color="#0091FF" size="28"></iconsfont
                    ></view>
                </view>
                <view class="consignee flex-s-s" v-else>
                    <view class="flex-start">
                        <view class="title">收货人</view>
                        <view class="name">请先添加收货人信息</view>
                    </view>
                    <view @click="goSelectAddress"
                        ><text class="style">选择</text
                        ><iconsfont customIcons="icon-xiayiji" color="#0091FF" size="28"></iconsfont
                    ></view>
                </view>
                <view class="consignee takeTheir flex-s-s">
                    <view style="flex: 1" @click="selectTake" v-if="TakeDelivery.ID">
                        <view>
                            <view class="flex-start"
                                ><view class="title">自提点</view
                                ><view class="name">{{ TakeDelivery.TakeDeliveryName }}</view></view
                            >
                            <text>{{ TakeDelivery.AddressDetail }}</text>
                        </view>
                    </view>
                    <view style="flex: 1" @click="selectTake" v-else>
                        <view>
                            <view class="flex-start"
                                ><view class="title">自提点</view><view class="name">请先添加自提点</view></view
                            >
                        </view>
                    </view>
                    <view @click="selectTake"
                        ><text class="style">{{ TakeDelivery.ID ? "切换" : "选择" }}</text
                        ><iconsfont customIcons="icon-xiayiji" color="#0091FF" size="28"></iconsfont
                    ></view>
                </view>
                <view class="uploadtime"
                    >下单时间：<text class="fs-24">{{ start_time }}</text>
                    <text class="fs-bold"
                        >预计<text class="fs-color">{{ HourNum + 24 }}</text
                        >小时后可提货</text
                    >
                </view>
                <view class="cart-list">
                    <cart-item
                        v-for="(item, index) in datas"
                        :key="item.ProductId"
                        :selectData="selectData"
                        :productInfo="item"
                        @upNum="upNum"
                        :orderType="23"
                        @changeCheck="changeCheck"
                        @checkboxChange="checkboxChange"
                        @delTip="delTip"
                        >{{ item.name }}</cart-item
                    >
                </view>
            </mescroll-uni>
        </view>

        <cart-bottom-bar
            ref="cartBottomBar"
            :isHome="true"
            :isEdit="isEdit"
            :selectData="selectData"
            :isShowSelect="isShowSelect"
            :getUseAddress="getUseAddress"
            :TakeDelivery="TakeDelivery"
            :productInfo="datas"
            :orderType="23"
            @selectAll="selectAll"
            @delCart="delCart"
            @isSelectAllBack="isSelectAllBack"></cart-bottom-bar>

        <uni-popup ref="delTip" type="dialog">
            <uni-popup-dialog
                type="text"
                title="温馨提示"
                content="确定删除该商品?"
                :before-close="true"
                @close="close"
                @confirm="doDel"></uni-popup-dialog>
        </uni-popup>
    </view>
</template>

<script>
import { mapMutations, mapGetters } from "vuex"
import cartItem from "@/components/cart/cart-item.vue"
import cartBottomBar from "@/components/cart/cart-bottom-bar.vue"
import { getReceivingAddressList, StatisPostageMoneyByUserCar } from "@/service/api/member.js"
import { GetAppointmentHourNum } from "@/service/api/communtiyGroup.js"

import { getUserCarList, deleteUserCar, updateCart } from "@/utils/cartUtil.js"
import utils from "@/utils/utils.js"
import { getElementHeight } from "@/uni-sub-base/utils/elementUtil.js"
import { GetUserDefaultTakeDelivery } from "@/service/api/takeDelivery.js"
import { eventBus } from "@/utils/eventBus.js"
export default {
    components: {
        cartItem,
        cartBottomBar,
    },
    props: {
        isHome: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            isEdit: false,
            isShowSelect: true,
            downOption: {
                use: true,
            },
            upOption: {
                empty: {
                    btnText: "立即购买",
                },
            },
            datas: [],
            isLoadOk: false,
            height: "",
            isEmpty: false,
            selectData: {
                proIds: [],
                ids: [],
            },
            isSelectAll: true,
            delPro: null,
            config: {
                title: "购物车",
                back: false,
                centerSlot: true,
                barPlaceholder: true,
                rightSlot: false,
                rightBtns: [
                    {
                        id: 1,
                        btnType: 1,
                        type: "编辑",
                    },
                ],
            },
            TakeDelivery: {},
            start_time: "",
            end_time: "",
            HourNum: "",
        }
    },
    created() {
        this.config.back = true
        this.$nextTick(() => {
            this.getListHeight()
        })
    },
    watch: {},
    computed: {
        ...mapGetters(["getUseAddress"]),
    },
    onload() {},
    onShow() {
        this.GetUserDefaultTakeDelivery() //默认自提点
    },
    mounted() {
        this.start_time = utils.getDateStr(null, 0) //今天
        this.end_time = utils.getDateStr(null, 1) //明天
        eventBus.$on("SET_CART", (msg) => {
            if (msg) {
                this.datas = msg
            }

            //购物车数据变化 更新UI
            this.upView()
            this.upBottom()
            if (this.isSelectAll) {
                this.selectAll(true)
            }
        })
        this.getAddress()
        this.GetUserDefaultTakeDelivery() //默认自提点
        this.GetAppointmentHourNum()
    },
    methods: {
        ...mapMutations(["SET_USE_ADDRESS"]),
        getAddress() {
            let param = {
                searchKey: "",
            }
            getReceivingAddressList(param).then((res) => {
                if (res.Data && res.Data.length > 0) {
                    let hasDefalut = false
                    res.Data.forEach((e) => {
                        if (e.IsDefault) {
                            hasDefalut = true
                            this.SET_USE_ADDRESS(e)
                        }
                    })
                    if (!hasDefalut) {
                        this.SET_USE_ADDRESS(res.Data[0])
                    }
                } else {
                    //还没有设置地址
                    this.SET_USE_ADDRESS(null)
                }
            })
        },
        selectTake() {
            if (this.TakeDelivery.ID) {
                uni.navigateTo({
                    url: "/pages_group/packet/group/takeTheirlist?from=selectBack&pagefrom=cart",
                    events: {
                        getSelectData: (data) => {
                            this.TakeDelivery = data.data
                        },
                    },
                })
            } else {
                // #ifdef APP-PLUS
                uni.navigateTo({
                    url: "/pages_group/packet/map/map-poi?from=selectBack",
                    events: {
                        getSelectData: (data) => {
                            this.TakeDelivery = data.data
                        },
                    },
                })
                // #endif
                // #ifdef  MP-WEIXIN
                uni.navigateTo({
                    url: "/pages_group/packet/map/map-poi-wx?from=selectBack",
                    events: {
                        getSelectData: (data) => {
                            this.TakeDelivery = data.data
                        },
                    },
                })
                // #endif
            }
        },
        GetUserDefaultTakeDelivery() {
            GetUserDefaultTakeDelivery({}).then((res) => {
                if (res.State == 1) {
                    this.TakeDelivery = res.Data
                } else {
                    if (res.Msg != "未设置可用的提货点") {
                        this.easyToast(res.Msg)
                    }
                }
            })
        },
        GetAppointmentHourNum() {
            GetAppointmentHourNum().then((res) => {
                if (res.State == 1) {
                    this.HourNum = res.Data
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        //获取列表高度
        getListHeight() {
            //获取商品高度
            getElementHeight(this, ".main", (e) => {
                e = e - 54 - uni.upx2px(150)

                this.height = e + "px"
                this.isLoadOk = true
                this.$nextTick(() => {
                    this.refresh()
                })
            })
        },
        //获取数据
        getData() {
            getUserCarList(true, 23).then((res) => {
                //OrderType＝23为社区团购
                this.datas = res
                if (res.length > 0) {
                    this.mescroll.endBySize(res.length, 1)
                } else {
                    this.isEmpty = true
                    this.mescroll.endBySize(0, 0)
                }
                this.upBottom()
                setTimeout(() => {
                    this.selectAll(true)
                }, 500)
            })
        },
        //更新UI
        upView() {
            if (this.mescroll) {
                this.mescroll.endBySize(this.datas.length, 1)
            }
        },
        //更新底栏
        upBottom() {
            if (this.$refs.cartBottomBar) {
                this.$refs.cartBottomBar.getTotal(this.datas)
            }
        },
        //刷新
        refresh() {
            this.mescroll.resetUpScroll()
        },
        //更新底栏数据
        upNum(e) {
            this.upBottom()
        },
        //去采购
        emptyClick() {
            this.easyGoTo("/pages/group/index")
        },
        //删除
        delCart(isClearAll) {
            if (isClearAll) {
                let ids = []
                this.datas.forEach((pro) => {
                    pro.SubItems.forEach((sub) => {
                        ids.push(String(sub.ID))
                    })
                })
                let param = {
                    ids: ids.join(","),
                    orderType: 23,
                }
                this.doDelCart(param)
            } else if (this.selectData.ids.length > 0) {
                let param = {
                    ids: this.selectData.ids.join(","),
                    orderType: 23,
                }
                this.doDelCart(param)
            }
        },
        //删除接口
        doDelCart(param) {
            uni.showLoading({
                title: "提交中",
            })
            deleteUserCar(param, 23).then((res) => {
                if (res) {
                    uni.hideLoading()
                    // this.refresh()
                    this.isEdit = false
                    this.setBtnText()
                    this.selectData.ids = []
                }
            })
        },
        //全选
        selectAll(e) {
            // this.isSelectAll = e
            let ids = []
            if (e) {
                this.datas.forEach((pro) => {
                    pro.SubItems.forEach((sub) => {
                        ids.push(String(sub.ID))
                    })
                })
            }
            this.setTreeSelect(ids)
        },
        //商品子项选择回调
        checkboxChange(e, id) {
            let values = e.detail.value
            if (values.length > 0) {
                this.selectData.ids.push(values[0])
            } else {
                this.selectData.ids.forEach((e, index) => {
                    if (e == id) {
                        this.selectData.ids.splice(index, 1)
                    }
                })
            }
            this.setTreeSelect(this.selectData.ids)
        },
        //数据处理
        setTreeSelect(ids) {
            //去重
            const set = new Set(ids)
            ids = [...set]
            this.selectData = {
                ids: ids,
            }
            this.$forceUpdate()
        },
        //单个商品全选or取消全选
        changeCheck(obj) {
            let isSelect = obj.isSelect
            let proId = obj.proId
            let subIds = obj.subIds
            if (isSelect) {
                //全选
                this.datas.forEach((e) => {
                    if (e.ProductId == proId) {
                        e.SubItems.forEach((sub) => {
                            this.selectData.ids.push(String(sub.ID))
                        })
                    }
                })
            } else {
                //取消全选
                for (var i = this.selectData.ids.length - 1; i >= 0; i--) {
                    let e = this.selectData.ids[i]
                    subIds.forEach((sub) => {
                        if (e == sub) {
                            this.selectData.ids.splice(i, 1)
                        }
                    })
                }
            }
            this.setTreeSelect(this.selectData.ids)
        },
        isSelectAllBack(e) {
            this.isSelectAll = e
        },
        close() {
            this.$refs.delTip.close()
        },
        doDel() {
            let obj = {
                ProductId: this.delPro.ProductId,
                Amount: 0,
                UnitId: this.delPro.UnitId,
                UnitName: this.delPro.DefaultUnit,
                skuId: this.delPro.SkuId,
                ratio: this.delPro.Ratio,
            }
            let param = []
            param.push(obj)
            updateCart(param, false, true, 23).then((res) => {})
            this.close()
        },
        delTip(e) {
            this.delPro = e
            this.$refs.delTip.open()
        },
        rightClick(e) {
            if (e.id == 1) {
                this.isEdit = !this.isEdit
                this.setBtnText()
            }
        },
        setBtnText() {
            this.config.rightBtns[0].type = this.isEdit ? "完成" : "编辑"
        },
        goSelectAddress() {
            let path = this.getUseAddress ? this.getUseAddress.ID : 0
            this.easyGoTo("/pages_me/packet/address/index?from=select&selectId=" + path)
        },
    },
}
</script>

<style lang="scss" scoped>
.container {
    // .bottom-bar {
    // 	/* #ifdef H5 */
    // 	bottom: 50px;
    // 	/* #endif */
    // }

    // .bottom-bar-mark {
    // 	/* #ifdef H5 */
    // 	height: 0;
    // 	/* #endif */
    // }
}

.cart-temp {
    // display: flex;
    // flex-direction: column;
}

.cart-list {
    padding: 0 $app-page-padding $app-page-padding $app-page-padding;
}

.car-title {
    font-weight: bold;
    font-size: 32rpx;
    color: $color-gray-1;
}
.consignee {
    margin: $app-page-padding $app-page-padding 0 $app-page-padding;
    padding: $app-page-padding;
    background: #fff;
    border-bottom: 2rpx solid #ebebeb;
    align-items: center;
}
.takeTheir {
    margin-top: 0;
}
.title {
    width: 102rpx;
    height: 44rpx;
    background: #eb1010;
    border-radius: 10rpx;
    color: #ffffff;
    font-size: 26rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 12rpx;
}
.style {
    font-size: 26rpx;
    color: #0091ff;
    font-weight: bold;
}
.name {
    font-weight: bold;
    font-size: 32rpx;
}
.uploadtime {
    background: #fff;
    margin: 0 $app-page-padding;
    padding: $app-page-padding;
    font-size: 28rpx;
    .fs-24 {
        font-size: 24rpx;
        padding-right: 24rpx;
    }
    .fs-bold {
        font-size: 28rpx;
        font-weight: bold;
    }
    .fs-color {
        font-size: 28rpx;
        font-weight: bold;
        color: #d81a32;
    }
}
</style>
